<template>
  <el-form ref="deptForm" :model="form" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in list" :key="item.id" :value="item.id" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getEmployeeSimple } from '@/api/employees'
import { newDepartment, getDepartmentDetails, putDepartment } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门负责人
        introduce: '' // 部门介绍
      },
      list: [] // 存放负责人列表
    }
  },
  // 页面加载就渲染
  created() {
    this.loadEmployeeSimple()
    // 如果就编辑状态就出发获取部门详细
    if (this.isEdit) { // isEdit 是true 的话 他就是编辑状态
      this.loadDepartmentDetails()
    }
  },
  methods: {
    // 获取部门详细
    async loadDepartmentDetails() {
      try {
        // 父组件传过来的id
        const res = await getDepartmentDetails(this.id)
        console.log(res)
        if (res.code === 10000) {
          this.form = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await putDepartment(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门
    async doAdd() {
      try {
        const res = await newDepartment({ pid: this.id, ...this.form })
        console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取负责人列表
    async loadEmployeeSimple() {
      const res = await getEmployeeSimple()
      console.log('负责人信息', res.data)
      this.list = res.data
    },
    // 确定
    hSubmit() {
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    // 取消
    hCancel() {

    }
  }
}
</script>
